/**
 * Created with JetBrains PhpStorm.
 * User: vander
 * Date: 5/9/13
 * Time: 9:55 PM
 * To change this template use File | Settings | File Templates.
 */
var MyBook = Class.create({
    initialize: function(o){
        // o : jsonObject
        this.name = o.name;
        this.id = o.id;

        this.resourcesPath = Global.localPath + o.resourcesPath;
        this.coverImage = o.coverImage;
        this.firstPageId = o.firstPageId;
        this.pages = new Array();

        this.attachedPagesId = new Array();

        for(var i =0 ; i < o.pages.length;i++){
            this.pages.push(new MyPage(this, o.pages[i]));
        }

        this.navigate(this.firstPageId);
    },
    navigate: function(pageId){


        var destPage = this.getPageById(pageId);

        if(destPage != null){
            //Remove nhung page khong lien quan den viec transition tu` fromPage den toPage
            // -->Muc tieu de lam` nhe. bot cay DOM
            for(var i =0 ; i < this.attachedPagesId.length;i++){
                if(this.attachedPagesId[i] != Global.currentPageId && this.attachedPagesId[i] != pageId){
                    this.attachedPagesId[i] = null;
                    var detachPage = this.getPageById(this.attachedPagesId[i]);
                    detachPage.detach();
                }
            }
            this.attachedPagesId = this.attachedPagesId.compact();

            //Them vao toPage
            this.attachedPagesId.push(pageId);
            //Attach toPage
            destPage.attach();
            Global.currentPageId = pageId;

            $j.mobile.changePage("#"+pageId, {transition: "flip"});
        }
    },
    getPageById: function(pageId){
        for(var i =0 ; i < this.pages.length;i++){
            if(this.pages[i].id == pageId){
                return this.pages[i];
            }
        }

        return null;
    },
    destroy: function(){
        for(var i =0 ; i < this.attachedPagesId.length;i++){

            var page = this.getPageById(this.attachedPagesId[i]);
            page.detach();
        }
    }
});